package com.duyus.ai.repository;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Properties;

@Slf4j
@Component
@RequiredArgsConstructor
public class MultiFileRepository {

    // 会话 ID 与 文件名的对应关系
    private final Properties chatFiles = new Properties();

    public boolean save(String chatId, Resource resource) {
        String filename = resource.getFilename();
        File target = new File(Objects.requireNonNull(filename));
        if (!target.exists()) {
            try {
                Files.copy(resource.getInputStream(), target.toPath());
            } catch (IOException e) {
                log.error("Failed to save PDF resource.", e);
                return false;
            }
        }

        chatFiles.put(chatId, filename);
        return true;
    }

    public Resource getFile(String chatId) {
        return new FileSystemResource(chatFiles.getProperty(chatId));
    }

    @PostConstruct
    private void init() {
        FileSystemResource pdfResource = new FileSystemResource("chat-pdf.properties");
        if (pdfResource.exists()) {
            try (Reader reader = new InputStreamReader(pdfResource.getInputStream(), StandardCharsets.UTF_8)) {
                chatFiles.load(reader);
            } catch (IOException e) {
                log.error("Failed to load chat-pdf.properties", e);
            }
        }

        // 加载每个文件
        chatFiles.forEach((key, value) -> {
            String chatId = (String) key;
            String filename = (String) value;
            log.info("Loading file: {} for chatId: {}", filename, chatId);
        });
    }

    @PreDestroy
    private void persistent() {
        try (Writer writer = new FileWriter("chat-pdf.properties")) {
            chatFiles.store(writer, LocalDateTime.now().toString());
        } catch (IOException e) {
            log.error("Failed to persist chat-pdf.properties", e);
        }
        log.info("File data is already persisted in the properties.");
    }

}